/**
 * Created by yadongw on 15-1-23.
 */
var UCX_Utils = {
	DATE_FORMAT_MMDDYYY : 1,
	getLocalTime : function(UTCTime, format){
		try{
			var UTCDate = this.getJsDate(UTCTime),
				offset = new Date().getTimezoneOffset(),
				localTimeStamp = UTCDate.getTime() - offset * 60 * 1000,
				localDate = new Date(localTimeStamp),
				localTime = '';
			if(format == this.DATE_FORMAT_MMDDYYY){
				localTime = localDate.toString().split(' ').slice(1,4);
				localTime = localTime[0] + " " + localTime[1] + ", " + localTime[2];
			}else{
				var year = localDate.getFullYear(),
					month = localDate.getMonth() + 1,
					date = localDate.getDate(),
					hour = localDate.getHours(),
					minute = localDate.getMinutes(),
					second = localDate.getSeconds();
				if( month < 10 ) month = '0' + month;
				if( date < 10 ) date = '0' + date;
				if( hour < 10 ) hour = '0' + hour;
				if( minute < 10 ) minute = '0' + minute;
				if( second < 10 ) second = '0' + second;

				localTime += year + "-";
				localTime += month + "-";
				localTime += date + " ";
				localTime += hour + ":";
				localTime += minute + ":";
				localTime += second;
			}

			return localTime;
		}catch (e){
			return '';
		}
	},

	isEmail : function (value)
	{
		if(value.match(/^[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/)){
			return true;
		}else{
			return false;
		}
	},
    isDomain : function (value)
    {
        if(value.match(/^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/)){
            return true;
        }else{
            return false;
        }
    },

	getTimePeriod : function (time)
	{
		var now = new Date(),
			date = this.getJsDate(time),
			interval = now - date,
			timePeriod,
			count;
		if(interval > 14 * 24 * 3600000){
			timePeriod = time;
		}else if(interval > 7 * 24 * 3600000){
			timePeriod = '1 week ago';
		}else if(interval >  24 * 3600000){
			count = Math.floor(interval / 24 / 3600000);
			timePeriod = count + (count > 1 ? ' days ago' : ' day ago');
		}else if(interval >  3600000){
			count = Math.floor(interval / 3600000);
			timePeriod = count + (count > 1 ? ' hours ago' : ' hour ago');
		}else if(interval >  60000){
			count = Math.floor(interval / 60000);
			timePeriod = count + (count > 1 ? ' minutes ago' : ' minute ago');
		}else if(interval >= 0){
			timePeriod = 'just now';
		}else{
			timePeriod = '';
		}
		return timePeriod;
	},

	//YYYY-MM-DD HH:ii:ss
	getJsDate : function(date)
	{
		var dateTime = date.split(' ');
		if(dateTime.length != 2) return '';
		var dates = dateTime[0].split('-');
		var times = dateTime[1].split(':');
		if(dates.length != 3 || times.length != 3) return '';

		return new Date(dates[0],dates[1] - 1,dates[2],times[0],times[1],times[2]);
	},

	confirm : function(content, callback)
	{
		$("#ucx_confirm .modal-body .modal-body-content").html(content);
		$("#ucx_confirm").modal('show');
		var callBackFun = function(){
			if(callback){
				callback();
			}
			$("#ucx_confirm").modal('hide');
		};
		$("#ucx_confirm .btn-primary").unbind('click').click(callBackFun);
	},

    alert : function(title, content, callback)
    {
		$("#ucx_alert .modal-title").html(title);
		$("#ucx_alert .modal-body .modal-body-content").html(content);
        $("#ucx_alert").modal('show');
	    var callBackFun = function(){
		    if(callback){
			    callback();
		    }
		    $("#ucx_alert").modal('hide');
	    };
	    $("#ucx_alert .btn-default").unbind('click').click(callBackFun);
    },

    htmlEncode : function(str)
    {
        return $('<div/>').text(str).html();
    },
    htmlDecode : function(str)
    {
        return $('<div/>').html(str).text();
    },

	getFileExt : function(filename)
	{
		var index = filename.lastIndexOf('.');
		if(index == -1){
			return '';
		}else{
			return filename.substring(index + 1).toLowerCase();
		}
	},

	getUrlParam : function(name) {
		var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");  
        var r = window.location.search.substr(1).match(reg);  
        if (r!==null) return unescape(r[2]); return null;  
	},	
	//type Should be error info success warning loading
	toast : function(type, content, options, title){
		var _options = {
			"positionClass" : "toast-top-center",
			"timeOut" : 4000	
		};
		
		if (type === 'loading'){
			_options.timeOut = 0;
			_options.extendedTimeOut = 0;
			_options.iconClasses ={info :'toast-loading'};
		}
		if (type === "error"){
			_options.timeOut = 10000;
			_options.closeButton = true;
		}
		if (type === "success"){
			_options.timeOut = 1000;
		}
		toastr.options = _.extend(_options, options);
		if (this.lastLoading){
			toastr.clear(this.lastLoading);
			this.lastLoading = null;
		}		
		if (type === 'loading'){
			this.lastLoading = toastr.info(content, title);
		}
		else{
			toastr[type](content, title);
		}
	},

	modal : function(dialogId, options){
		var $dialog = $("#"+ dialogId);
		var $form = $dialog.find("form");
        var submitForm_cb = null;
        if (typeof options.submitForm == 'function')
        {
           submitForm_cb =  _.once(options.submitForm, 3000);
        }

		function okCallback(){
			if (typeof options.okCallback == "function"){
				options.okCallback();
			}
		}
		function showCallback(){
			if ($form.length > 0){
				$form[0].reset();
			}
			$dialog.find(":text,:file").val("");
			$dialog.find(":submit").removeClass("disabled").removeAttr("disabled");				
			if (typeof options.showCallback == "function"){
				options.showCallback();
			}
		} 
		function hideCallback(){			 
			if (typeof options.hideCallback == 'function'){
				options.hideCallback();
			}
		}		
		function submitForm(event){			
			if (typeof submitForm_cb == "function"){
                event.stopPropagation();
                event.preventDefault();
				event.result = false;    
				$dialog.find(":submit").addClass("disabled").attr("disabled", "disabled");
                submitForm_cb($form, $dialog.find(":file"));
			}
		}		
		function shownCallback(event){
			if (typeof options.shownCallback == 'function'){
				options.shownCallback();
			}
		}
  		$dialog.on('show.bs.modal', showCallback);
  		$dialog.on('shown.bs.modal', shownCallback);
  		$dialog.on('hide.bs.modal', hideCallback);
  		$dialog.on('click', '.btn-danger', okCallback);
  		$dialog.on('hidden.bs.modal', function(){
  			$dialog.off('show.bs.modal', showCallback);
  			$dialog.off('shown.bs.modal', shownCallback);
			$dialog.off('hide.bs.modal', hideCallback);
			$dialog.off('click', '.btn-danger', okCallback);
			$form.off("beforeSubmit", submitForm);
            //$form.off("submit", submitForm);
  		});
  		$form.on("beforeSubmit", submitForm);
        //$form.on("submit", submitForm);
		return {
			show: function(){
				$dialog.modal("show");
				return this;
			},
			hide: function(){
				$dialog.modal("hide");
			}
		};
	}
};

String.prototype.format = function(args) {
	if (arguments.length > 0) {
		var result = this;
		if (arguments.length == 1 && typeof(args) == "object") {
			for (var key in args) {
				var reg = new RegExp("({" + key + "})", "g");
				result = result.replace(reg, args[key]);
			}
		} else {
			for (var i = 0; i < arguments.length; i++) {
				if (arguments[i] == undefined) {
					return "";
				} else {
					var reg = new RegExp("({[" + i + "]})", "g");
					result = result.replace(reg, arguments[i]);
				}
			}
		}
		return result;
	} else {
		return this;
	}
};

Number.prototype.toPercent = function(){
	return (Math.round(this * 10000)/100).toFixed(2) + '%';
}

function classNames(){
	var count = arguments.length;	
    var ret = "";
    for (var i = 0; i < count; i++){
    	var classes = arguments[i];
		if (typeof classes == 'object') {
			for (var prop in classes) {
				if (classes[prop]) {
					ret += prop;
					ret += " ";
				}
			}
		}
		if (typeof classes == "string"){
			ret += classes;
			ret += " ";
		}
	}
    return ret;
}

function bytes(bytes, precision){	
	var number, units;
    if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) {
      return '-';
    }
    if(parseInt(bytes) == 0){
    	return "0 byte";
    }
    if (typeof precision === 'undefined') {
      precision = 1;
    }
    units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
    number = Math.floor(Math.log(bytes) / Math.log(1024));
    return (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision) + ' ' + units[number];
}

function reject(reason) {//构造处在错误状态的promise对象
  var dfr = $.Deferred();
  dfr.reject(reason);
  return dfr.promise();
}

$.browser = $.browser || {}
$.browser.mozilla = /firefox/.test(navigator.userAgent.toLowerCase());
$.browser.webkit = /webkit/.test(navigator.userAgent.toLowerCase());
$.browser.opera = /opera/.test(navigator.userAgent.toLowerCase());
$.browser.msie = /msie/.test(navigator.userAgent.toLowerCase());

(function($){
	$.fn.loading = function(options) {		
		return this.each(function(){			
			if ($(this).parent().find("#loading-tag").length === 0){
				$(this).hide().after('<div id="loading-tag" style="text-align:center;padding:20px"><img src="/img/input-spinner.gif"></img></div>');
			}
		});
	};
	$.fn.endLoad = function(options) {	
		return this.each(function() {			
			$(this).show().parent().find("#loading-tag").remove();
		});
	};
	$.fn.setCursorPosition = function(option) {
	    var settings = $.extend({
	        index: 0
	    }, option)
	    return this.each(function() {
	        var elem  = this
	        var val   = elem.value
	        var len   = val.length
	        var index = settings.index
			if (settings.index == -1){
				index = len;
			}
	 
	        // 非input和textarea直接返回
	        var $elem = $(elem)
	        if (!$elem.is('input,textarea')) return
	        // 超过文本长度直接返回
	        if (len < index) return
	 
	        setTimeout(function() {
	            elem.focus()
	            if (elem.setSelectionRange) { // 标准浏览器
	                elem.setSelectionRange(index, index)   
	            } else { // IE9-
	                var range = elem.createTextRange()
	                range.moveStart("character", -len)
	                range.moveEnd("character", -len)
	                range.moveStart("character", index)
	                range.moveEnd("character", 0)
	                range.select()
	            }
	        }, 100)
	    })
}
})(jQuery);